package com.jeeplus.modules.guide.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.guide.service.YmbcsMatterService;
import com.jeeplus.modules.guide.utils.HttpGetWithEntity;
import com.jeeplus.modules.guide.utils.HttpRequestUtil;
import com.jeeplus.modules.sys.entity.MobileRC;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.EncryptUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Api(tags = "授权")
@RequestMapping("/authorization")
@RequiredArgsConstructor
public class AuthorizationController {
    @Value("${AUTHORIZATION_URL}")
    private String AUTHORIZATION_URL;
    @Value("${appkey}")
    private String appkey;
    //#人才调用url获取code
    @Value("${rcCodeUrl}")
    private String rcCodeUrl;
    //私钥
    @Value("${GX_PUBLIC_KEY}")
    private String GX_PUBLIC_KEY;
    private static final Logger log = LoggerFactory.getLogger(AuthorizationController.class);
    private final UserService userService;
    private final YmbcsMatterService ymbcsMatterService;
    @GetMapping(value ="getAuthorizationIsTrue")
    @ApiOperation(value ="身份证查看授权是否在有效期内")
    public AjaxJson getAuthorizationIsTrue(){
        if (null == UserUtils.getUser()) {
            return AjaxJson.error("未登录！").put("code",400);
        }
        MobileUserQR qr = userService.getUserIdcard(UserUtils.getUser().getLoginName());
        if (null == qr) return AjaxJson.error("未登录！").put("code",400);
        if(checkID(qr.getIdcard())){
        String reqParams = JSONObject.fromObject("{\"query\": {\"8959\": \""+qr.getIdcard()+"\"}}").toString();
            String s="";
        try {
            s = sendJsonByGetReq(AUTHORIZATION_URL, reqParams, "UTF-8",appkey);
            log.error("授权请求Get请求返回结果："+s);
        } catch (Exception e) {
            e.printStackTrace();
        }
            JSONArray jsonArray = JSONArray.fromObject(s);
            List<String> list=new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            for (int i = 0; i < jsonArray.size(); i++) {

                String a=jsonArray.getJSONObject(i).getJSONObject("mapped_values").getJSONObject("agent_id_card_number").getString("value");
                String substring = a.substring(2, a.length() - 2);
                if (qr.getIdcard().equals(substring)){
                    String string = jsonArray.getJSONObject(i).getJSONObject("mapped_values").getJSONObject("date_range").getString("value");
                    String substring1 = string.substring(2, string.length() - 2);
                    String[] split = substring1.split(" - ");
                    try {
                        long time = format.parse(split[1]).getTime();
                        long dqtime = new Date().getTime();
                        if(time>=dqtime){
                            if("集体户管理".equals(jsonArray.getJSONObject(i).getJSONObject("mapped_values").getJSONObject("auth_event").getJSONArray("value").getString(0))){
                                ymbcsMatterService.intoRC(jsonArray.getJSONObject(i).getJSONObject("mapped_values").getJSONObject("name").getJSONArray("value").getString(0),jsonArray.getJSONObject(i).getString("mapped_values"),"集体户管理",UserUtils.getUser().getLoginName());
                                list.add(jsonArray.getJSONObject(i).getJSONObject("mapped_values").getJSONObject("name").getJSONArray("value").getString(0));
                            }
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(list.size()!=0){
                        return AjaxJson.success("请求成功！").put("data",list);
                    }else {
                        return AjaxJson.error("暂无授权数据！").put("code",400);
                    }
                }
            }

        }

        return AjaxJson.error("请求失败！").put("code",400);
    }




    @GetMapping(value ="toAuthorizationIsTrue")
    @ApiOperation(value ="授权信息绑定")
    public AjaxJson toAuthorizationIsTrue(String name) throws UnsupportedEncodingException {
        if (null == UserUtils.getUser()) {
            return AjaxJson.error("未登录！").put("code",400);
        }
        String result = "code="+HttpRequestUtil.getRCCode(rcCodeUrl);
        MobileRC userRC = userService.getUserRC(UserUtils.getUser().getLoginName());
        if(StringUtils.isNotBlank(name)){
            JSONObject json = JSONObject.fromObject(ymbcsMatterService.selectRC(UserUtils.getUser().getLoginName(),name));
            result += "&username="+json.getJSONObject("name").getJSONArray("value").getString(0)+"&idCard="+json.getJSONObject("id_card_number").getJSONArray("value").getString(0)+"&phone="+json.getJSONObject("phone").getJSONArray("value").getString(0)+"&agentName="+userRC.getName();
        }else{
            result += "&username="+userRC.getName()+"&idCard="+userRC.getIdcard()+"&phone="+userRC.getTell()+"&agentName=";
        }
        return AjaxJson.success().put("data", Base64.encodeBase64String(result.getBytes("utf-8")));
    }


    public static String sendJsonByGetReq(String url, String param, String encoding,String appkey) throws Exception {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url,appkey);
        HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpGetWithEntity.setEntity(httpEntity);
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpGetWithEntity);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        //释放链接
        response.close();
        return body;
    }
    public static boolean checkID(String s) {
        //空参判断，保证程序健壮性
        if (s == null) {
            return false;
        }
        //判断长度
        if (s.length() != 18) {
            return false;
        }
        //public boolean startsWith​(String prefix)
        //测试此字符串是否以指定的前缀开头。
        if (s.startsWith("0")) {
            return false;
        }
        //遍历字符串
        for (int i = 0; i < s.length(); i++) {
            //获取遍历字符
            char ch = s.charAt(i);
            //最后一位的校验
            if (i == s.length() - 1) {
                //优化程序，改变逻辑判断
                if (ch < '0' || ch > '9' && ch != 'X') {
                    return false;
                }
            } else {//其他位的校验
                if (ch < '0' || ch > '9') {
                    return false;
                }
            }
        }
        //以上都不符合，返回true
        return true;
    }
}
